﻿using Dm.filter;
using Microsoft.AspNetCore.Mvc;
using xxx.Candidates.System.Common.Helpers;
using xxx.Candidates.System.Common.Redis;
using xxx.Candidates.System.Common.Utilities;
using xxx.Candidates.System.Hostd.Authorization;
using xxx.Candidates.System.Hostd.Extensions;
using xxx.Candidates.System.Interfaces.IService;
using xxx.Candidates.System.Model;
using xxx.Candidates.System.Model.Dto;
using xxx.Candidates.System.Model.View;

namespace xxx.Candidates.System.Hostd.Controllers.System
{
    /// <summary>
    /// 用户验证
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AuthController : BaseController
    {
        /// <summary>
        /// 会话管理接口
        /// </summary>
        private readonly TokenManager _tokenManager;

        /// <summary>
        /// 日志管理接口
        /// </summary>
        private readonly ILogger<AuthController> _logger;

        /// <summary>
        /// 用户服务接口
        /// </summary>
        private readonly ISysUsersService _userService;

        public AuthController(TokenManager tokenManager, ISysUsersService userService, ILogger<AuthController> logger)
        {
            _tokenManager = tokenManager;
            _userService = userService;
            _logger = logger;
        }

        [HttpPost]
        public IActionResult Login([FromBody] LoginDto parm)
        {
            var userInfo = _userService.GetFirst(o => o.UserID == parm.UserName.Trim());

            if (userInfo == null)
            {
                return toResponse(StatusCodeType.Error, "用户名或密码错误");
            }

            if (!PasswordUtil.ComparePasswords(userInfo.UserID, userInfo.Password, parm.PassWord.Trim()))
            {
                return toResponse(StatusCodeType.Error, "用户名或密码错误");
            }

            var userToken = _tokenManager.CreateSession(userInfo, Convert.ToInt32(AppSettings.Configuration["AppSettings:WebSessionExpire"]));

            return toResponse(userToken);
        }

        /// <summary>
        /// 用户退出
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult LogOut()
        {
            _tokenManager.RemoveSession(_tokenManager.GetSysToken);

            return toResponse(StatusCodeType.Success);
        }

        /// <summary>
        /// 用户信息获取
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorization]
        public IActionResult GetUserInfo()
        {
            UserSessionVM userSessionVM = _tokenManager.GetSessionInfo();

            return toResponse(userSessionVM);
        }
    }
}
